package com.driving.code.config;

import com.driving.code.realm.UserRealm;
import com.driving.code.utils.MyModularRealmAuthenticator;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;


/**
 * Created with IntelliJ IDEA.
 * 作者: 喜欢编程的代先生
 * 日期: 2021/6/15
 * 时间: 20:09
 * 描述: shiro的配置
 */
@Configuration
public class ShiroConfig {

    /**
     * 创建UserRealm
     * @return
     */
    @Bean
    public UserRealm getUserRealm(){
        //创建自定义的Realm
        UserRealm userRealm = new UserRealm();
        //创建凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置凭证匹配器采用md5算法进行加密
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置Hash散列次数
        credentialsMatcher.setHashIterations(1024);
        //给Realm设置凭证匹配器
        userRealm.setCredentialsMatcher(credentialsMatcher);
        return userRealm;
    }

    @Bean
    public MyModularRealmAuthenticator myModularRealmAuthenticator(){
        MyModularRealmAuthenticator myModularRealmAuthenticator = new MyModularRealmAuthenticator();
        return myModularRealmAuthenticator;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //配置自定义认证器(放在realms设置之前)
        securityManager.setAuthenticator(myModularRealmAuthenticator());
        Collection<Realm> realms = new ArrayList<>();
        realms.add(getUserRealm());
        securityManager.setRealms(realms);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultSecurityManager securityManager){
        //创建Shiro的过滤器
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilter.setSecurityManager(securityManager);
        //设置未认证的时候访问的页面
        shiroFilter.setLoginUrl("/page/backLogin");
        //设置没有权限的时候访问的页面
        shiroFilter.setUnauthorizedUrl("/page/unauthorized");
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        //设置可以进行匿名访问
        linkedHashMap.put("/page/backLogin","anon");
        //设置指定角色才能进行访问
        linkedHashMap.put("/page/back*","roles[admin]");
        shiroFilter.setFilterChainDefinitionMap(linkedHashMap);
        return shiroFilter;
    }
}
